package com.zsummer.zero.dbpool.dbcp;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import com.zsummer.zero.dbpool.Actor;

/**
 * 使用dbcp连接池获取连接
 * @author zhouyujiang
 *
 */
public class Demo2 {
	
	static String userName = "root";
	static String password = "root";
	static String driverName = "com.mysql.cj.jdbc.Driver";
	static String url = "jdbc:mysql://localhost:3306/sakila?useSSL=true&characterEncoding=utf8&serverTimezone=UTC";
	
	public static void main(String[] args) {
		Properties prop = new Properties();
		prop.setProperty("username", userName);
		prop.setProperty("password", password);
		prop.setProperty("driverClassName", driverName);
		prop.setProperty("url", url);
		try {
			DataSource datasource = BasicDataSourceFactory.createDataSource(prop);
			Connection conn = datasource.getConnection();
			System.out.println(conn);
			
			String sql = "select * from actor";
			PreparedStatement ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			
			ArrayList<Actor> actors = new ArrayList<Actor>();
			while(rs.next()) {
				int actorId = rs.getInt("actor_id");
				String firstName = rs.getString("first_name");
				String lastName = rs.getString("last_name");
				Date lastUpdate = rs.getDate("last_update");
				Actor actor = new Actor();
				actor.setActorId(actorId);
				actor.setFirstName(firstName);
				actor.setLastName(lastName);
				actor.setLastUpdate(lastUpdate);
				actors.add(actor);
			}
			
			for (Actor actor : actors) {
				System.out.println(actor);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
